
import schema from 'async-validator';
import { OrderSide, PositionSide } from 'binance';
import { errLogger } from 'ROOT/common/logger';
import { AppContext } from 'ROOT/interface/App';
import { AutoOrderConfig, AutoTradeType } from 'ROOT/trader';
import { traderRobot } from 'ROOT/TraderRobot';
import SymbolOrderConfigService from "../symbol-order-config/SymbolOrderConfig.service";

/**
 * 下单
 */
export const submitOrder = async (ctx: AppContext) => {
  const body = ctx.request.body as Record<string, any>;
  const validator = new schema({
    symbol: {
      type: "string",
      required: true
    },
    tradeType: {
      type: "string",
      required: true
    },
    action: {
      type: "string",
      required: true
    },
    positionSide: {
      type: "string",
    },
    orderType: {
      type: "string",
      required: true
    },
    depthRangeDis: {
      type: "number",
    },
    positionsRate: {
      type: "number",
    },
    quantity: {
      type: "number",
    },
    price: {
      type: "number",
    }
  });
  try {
    await validator.validate(body);
  } catch (err) {
    console.log(err)
    ctx.sendError(err);
    return;
  }
  const userId = ctx.state.user && ctx.state.user.id;

  const userTrader = traderRobot.trader.findUserTrader(userId);

  try {
    if (!userTrader) {
      return ctx.sendError({message: `findUserTrader(${userId})`});
    }
    const orderConfig = await SymbolOrderConfigService.findOne({symbol: body.symbol, userid: userId, trade_type: body.tradeType})
    await userTrader.submitOrder({
      orderConfig: orderConfig as AutoOrderConfig,
      ...body,
    } as {
      symbol: string;
      action: OrderSide;
      tradeType: AutoTradeType;
      orderType: AutoOrderConfig['order_type'];
      positionSide?: PositionSide;
      depthRangeDis?: number;
      orderConfig: AutoOrderConfig;
      positionsRate?: number;
      quantity?: number;
      price?: number;
    })
    ctx.sendSuccess({});
  } catch (error) {
    ctx.sendError({ message: error });
  }
}


/**
 * 平单
 */
// export const closeAllOrder = async (ctx: AppContext) => {
//   const body = ctx.request.body as Record<string, any>;
//   const validator = new schema({
//     symbol: {
//       type: "string",
//       required: true
//     },
//     trade_type: {
//       type: "string",
//       required: true
//     }
//   });
//   try {
//     await validator.validate(body);
//   } catch ({ errors, fields }) {
//     ctx.sendError({ errors });
//     return;
//   }
//   const userId = ctx.state.user.id;
//   try {
//     await traderRobot.trader.closeAllOrder(userId, body.symbol, body.trade_type);
//     ctx.sendSuccess({});
//   } catch (error) {
//     ctx.sendError({ message: error });
//   }
// }

/** 止盈 */
// export const stopOrder = async (ctx: AppContext) => {
//   const body = ctx.request.body as Record<string, any>;
//   const validator = new schema({
//     symbol: {
//       type: "string",
//       required: true
//     },
//     positionSide: {
//       type: "string",
//       required: true
//     },
//     tradeType: {
//       type: "string",
//       required: true
//     }
//   });
//   try {
//     await validator.validate(body);
//   } catch ({ errors, fields }) {
//     ctx.sendError({ errors });
//     return;
//   }
//   const userId = ctx.state.user.id;

//   const userTrader = traderRobot.trader.findUserTrader(userId);
//   if (!userTrader) {
//     ctx.sendError({ message: "trader.findUserTrader" });
//     return;
//   }
//   try {
//     if (body.tradeType === 'futures') {
//       await userTrader.stopFuturesOrder(body.symbol, body.positionSide);
//     } else if (body.tradeType === 'delivery') {
//       await userTrader.stopDeliveryOrder(body.symbol, body.positionSide);
//     }
//     ctx.sendSuccess({});
//   } catch (error) {
//     errLogger.error(error)
//     ctx.sendError({ message: error.message });
//   }
// }

export const triggerOrder = async (ctx: AppContext) => {
  const query = ctx.request.query as Record<string, any>;
  const userId = query.userid;

  try {
    await traderRobot.trader.beforeOrder(Number(query.strategy_id), {
      symbol: query.symbol,
      close: query.close,
    } as any, query.action);
    ctx.sendSuccess({ data: { userId } });
  } catch (error) {
    ctx.sendError({ message: error.message });
  }
}
